from rest_framework import viewsets, status
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.utils import timezone
from datetime import datetime, timedelta, date
import logging
from ..models import Event, Calendar
from ..serializers import CalendarSerializer


logger = logging.getLogger('apps')


class BaseResponse:
    """基础响应类"""

    @staticmethod
    def success(data=None, message="操作成功"):
        return Response({
            "status": "success",
            "message": message,
            "data": data
        })

    @staticmethod
    def error(message="操作失败", status=status.HTTP_400_BAD_REQUEST):
        return Response({
            "status": "error",
            "message": message
        }, status=status)


class CalendarViewSet(viewsets.ReadOnlyModelViewSet):
    """日历视图集"""
    serializer_class = CalendarSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Calendar.objects.filter(date__year=timezone.now().year)

    @action(detail=False, methods=['get'])
    def current_month(self, request):
        """获取当月日历数据"""
        try:
            # 获取年月参数
            year = request.query_params.get('year')
            month = request.query_params.get('month')

            # 如果没有提供，使用当前年月
            if not year or not month:
                today = timezone.now()
                year = today.year
                month = today.month
            else:
                year = int(year)
                month = int(month)

            # 获取月份的第一天和最后一天
            first_day = datetime(year, month, 1).date()
            if month == 12:
                last_day = datetime(year + 1, 1, 1).date() - timedelta(days=1)
            else:
                last_day = datetime(year, month + 1, 1).date() - timedelta(days=1)

            # 获取用户在该月的所有日程
            events = Event.objects.filter(
                user=request.user,
                date__gte=first_day,
                date__lte=last_day
            )

            # 按日期分组统计
            daily_stats = {}
            for day in range(1, last_day.day + 1):
                date_obj = datetime(year, month, day).date()
                date_str = date_obj.strftime('%Y-%m-%d')

                # 初始化每天的统计数据
                daily_stats[date_str] = {
                    'total': 0,
                    'completed': 0,
                    'pending': 0,
                    'high_priority': 0,
                    'medium_priority': 0,
                    'low_priority': 0
                }

            # 统计每天的日程数据
            for event in events:
                date_str = event.date.strftime('%Y-%m-%d')
                if date_str in daily_stats:
                    daily_stats[date_str]['total'] += 1

                    # 统计完成状态
                    if event.status == 'completed':
                        daily_stats[date_str]['completed'] += 1
                    elif event.status == 'pending':
                        daily_stats[date_str]['pending'] += 1

                    # 统计优先级
                    if event.importance == 'high':
                        daily_stats[date_str]['high_priority'] += 1
                    elif event.importance == 'medium':
                        daily_stats[date_str]['medium_priority'] += 1
                    elif event.importance == 'low':
                        daily_stats[date_str]['low_priority'] += 1

            # 计算月度总结
            month_summary = {
                'total_events': events.count(),
                'completed_events': events.filter(status='completed').count(),
                'pending_events': events.filter(status='pending').count(),
                'high_priority_events': events.filter(importance='high').count(),
                'medium_priority_events': events.filter(importance='medium').count(),
                'low_priority_events': events.filter(importance='low').count(),
                'busiest_day': max(daily_stats.items(), key=lambda x: x[1]['total'])[0] if daily_stats else None,
                'most_productive_day': max(daily_stats.items(), key=lambda x: x[1]['completed'])[
                    0] if daily_stats else None
            }

            return BaseResponse.success({
                'year': year,
                'month': month,
                'days_in_month': last_day.day,
                'first_day_weekday': first_day.weekday(),
                'daily_stats': daily_stats,
                'month_summary': month_summary
            })
        except Exception as e:
            return BaseResponse.error(f"获取月度日历数据失败: {str(e)}")